
import asyncio
import json
import logging
import uuid
from datetime import datetime
from mcp.client.stdio import stdio_client
from mcp import ClientSession, StdioServerParameters

# 配置日志记录器
logging.basicConfig(
    level=logging.DEBUG,  # 设置为DEBUG以捕捉全部日志信息
    format="%(asctime)s | %(levelname)s | %(message)s",
    handlers=[
        logging.FileHandler("mcp_debug.log", encoding="utf-8"),
        logging.StreamHandler()
    ]
)

# 配置服务端启动命令
server_params = StdioServerParameters(
    command="uv",
    args=["run", "math_agent.py"]
)

# 定义请求上下文元信息生成函数
def generate_metadata():
    return {
        "request_id": str(uuid.uuid4()),
        "timestamp": datetime.utcnow().isoformat(),
        "caller": "client.logger.demo",
        "env": "debug"
    }

# 封装日志打印函数
def log_request_response(prompt, result):
    logging.info("=== 请求Prompt结构 ===")
    logging.info(json.dumps(prompt, ensure_ascii=False, indent=2))
    logging.info("=== 响应内容 ===")
    for content in result.content:
        logging.info(content.text)
    logging.info("Trace ID: %s", getattr(result, "trace_id", "N/A"))

async def main():
    # 与服务端建立连接
    async with stdio_client(server_params) as (stdio, write):
        async with ClientSession(stdio, write) as session:
            await session.initialize()

            # 构造请求Prompt
            prompt = [
                {"role": "system", "content": "你是一个日志演示助手"},
                {"role": "user", "content": "请计算 12 与 7 的和"}
            ]

            # 构造调用参数
            params = {
                "model": "deepseek-chat",
                "prompts": prompt,
                "metadata": generate_metadata(),
                "config": {
                    "temperature": 0.5,
                    "max_tokens": 128,
                    "stream": False
                }
            }

            # 发起工具调用
            logging.info("准备调用工具 'add'")
            result = await session.call_tool("add", {"x": 12, "y": 7})

            # 打印详细结构日志
            log_request_response(prompt, result)

if __name__ == "__main__":
    asyncio.run(main())